﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Net;
using Utility;
using SuperSocket.Common;
using SuperSocket.Facility;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using AIEventControlLibrary;
using Newtonsoft.Json;
namespace AISmartEventServer
{

    //主要事件接收
    /// <summary>
    ///  主要事件数据接收
    /// </summary>
    public class AlarmMsgManager
    {
        public static String SocketIP = "";
        public string jason;
        public bool isRun = true;
        private Thread thSend = null;
        private Thread thInsert = null;
        List<ServerModel> listServer = new List<ServerModel>();
        ZSDDBHelper.DBHelper dbHelper = new ZSDDBHelper.DBHelper();
         public static SuperSocketServer supersocketserver = new SuperSocketServer();
        public SuperSocketServer super
        {
            get { return supersocketserver; }
        }
        /// <summary>
        ///  StartServer 启动
        /// </summary>
        public bool StartServer()
        {
            try
            {
                SocketIP = System.Configuration.ConfigurationManager.AppSettings["SocketIP"];
                string SocketPort = System.Configuration.ConfigurationManager.AppSettings["SocketPort"];
                int port = string.IsNullOrEmpty(SocketPort) ? 50001 : Convert.ToInt32(SocketPort);
                supersocketserver.Login(SocketIP, port);

                listServer = ReadAiServerXml();
                //
                foreach (var model in listServer)
                {
                    VodeoAlarmMsg.StartAlarm(model.IP,model.Port,model.UserID,model.PassWord);
                }

                //// 消息发送
                //thSend = new Thread(MessageSend);
                //thSend.IsBackground = true;
                //thSend.Start();

                // 消息插入
                thInsert = new Thread(AlarmDataManager);
                thInsert.IsBackground = true;
                thInsert.Start();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.InstanctLogHelper.WriteLog("StartServer Err：" + ex.ToString());
            }
            return false;
        }
        /// <summary>
        ///  停止
        /// </summary>
        /// <returns></returns>
        public bool StopServer()
        {
            //Utility.ThreadManager.CloseThread(thSend);
            Utility.ThreadManager.CloseThread(thInsert);
            return true;
        }

        #region 报警信息发送
        private void MessageSend()
        {
            string strMsg = "";
            while (isRun)
            {
                try
                {
                    strMsg = AlarmEventDataCache.GetAlarmXmlMsg();
                    if (string.IsNullOrEmpty(strMsg))
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        for (int i = 0; i < supersocketserver.listSession.Count; i++)
                        {   
                            supersocketserver.listSession[i].Send(strMsg);

                        }
                    }
                }
                catch (Exception ex)
                {
                    Utility.LogHelper.InstanctLogHelper.WriteLog("MessageSend Err" + ex.Message);
                }
            }
        }
        #endregion

        #region 报警信息入库管理
        /// <summary>
        /// AlarmDataManager
        /// </summary>
        private void AlarmDataManager()
        {
            AIEventControlLibrary.Data.EventRecord recordModel = null;
            AlarmMessageModel alarmMessageModel = new AlarmMessageModel();
            int tempPort = 8895;
           // string tempUrl = "";
            while (isRun)
            {
                try
                {
                    recordModel = AlarmEventDataCache.GetAlarmDataMsg();
                    if (recordModel == null)
                    {
                        Thread.Sleep(100);
                    }
                    else
                    {
                        var model= listServer.Find(f=>(f.IP+"-"+f.Port)==recordModel.KeyID);

                        if (model != null)
                        {
                            if (!string.IsNullOrEmpty(recordModel.Pic1))
                            {
                                recordModel.Pic1 = "http://" + model.IP + ":" + tempPort + "/DownloadImageFile" + string.Format("?ImageFilePath={0}", recordModel.Pic1);
                            
                            } if (!string.IsNullOrEmpty(recordModel.Pic2))
                            {
                                recordModel.Pic2 = "http://" + model.IP + ":" + tempPort + "/DownloadImageFile" + string.Format("?ImageFilePath={0}", recordModel.Pic2);
                            } if (!string.IsNullOrEmpty(recordModel.Pic3))
                            {
                                recordModel.Pic3 = "http://" + model.IP + ":" + tempPort + "/DownloadImageFile" + string.Format("?ImageFilePath={0}", recordModel.Pic3);
                            }
                            // 先消息发送
                            string strMsg = JsonConvert.SerializeObject(recordModel);
                            for (int i = 0; i < supersocketserver.listSession.Count; i++)
                            {
                                supersocketserver.listSession[i].Send(strMsg);
                            }

                            //记录查询
                            alarmMessageModel = new AlarmMessageModel
                            {
                                ID = Utility.GuidFormat.NewGuidN,
                                SOURCEID = recordModel.ChnId.ToString(),
                                AlarmName = recordModel.Text,
                                AlarmTime = recordModel.Time,
                                AlarmType = (int)recordModel.RuleType,
                                IvsHostFeedId = recordModel.Id,
                                RuleType = recordModel.RuleType.ToString(),
                                AlarmImage = recordModel.Pic1,
                                BeginTakePic = recordModel.Pic2,
                                EndTakePic = recordModel.Pic3,
                                AreaIndex = recordModel.AreaNo,
                                AlarmLevel = recordModel.Level,
                                RuleIndex = recordModel.RuleId,
                                EStatus = BaseCommon.EntityStatus.Inserted,
                                StopAlarmTime = DateTime.Now,
                                UpdateTime = DateTime.Now,
                                AlarmCount = 0,
                                sysid = recordModel.KeyID,
                                ServerID = (model == null ? "1" : model.ID),
                            };

                            dbHelper.InsertTableDB("AIEventAlarmRecord", alarmMessageModel);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.InstanctLogHelper.WriteLog("AlarmDataManager Err" + ex.Message);
                }
            }
        }

        public string ImageString64(string Url)
        {
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(Url);
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            return sReturnString;
                        }
                    }
                }
            }
        }
        #endregion

        #region   AI分析服务器信息读取
        /// <summary>
        /// AI分析服务器信息读取
        /// </summary>
        /// <returns></returns>
        private List<ServerModel> ReadAiServerXml()
        {
            try
            {
                string path = AppSetting.GetAppPath + "\\AIServer.xml";
                DataSet ds = new DataSet();
                ds.ReadXml(path);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    return Utility.DataConverter.ConvertToDataList<ServerModel>(ds.Tables[0]);
                }
            }
            catch( Exception ex)
            {
                LogHelper.InstanctLogHelper.WriteLog("ReadAiServerXml Err" + ex.Message);
            }
            return new List<ServerModel>();
        }

        #endregion



       
    }
}


